package newkfp;

import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

@ManagedBean(name = "employeeController")
@SessionScoped
public class EmployeeController implements Serializable {

    Loger loger;
    @EJB
    private newkfp.LogFacade logFacade;
    private Employee current;
    private DataModel items = null;
    @EJB
    private newkfp.EmployeeFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String userName;
    private String password;
    private int limits;
    HttpSession session;

    public int getLimits() {
        session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        limits = (Integer) session.getAttribute("limits");
        return limits;
    }

    public void setLimits(int limits) {
        this.limits = limits;
    }

    public EmployeeController() {
    }

    public Employee getSelected() {
        if (current == null) {
            current = new Employee();
            selectedItemIndex = -1;
        }
        return current;
    }

    private EmployeeFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(getFacade().count()) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        current = null;
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Employee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Employee();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("EmployeeCreated"));
            loger.LogerString("اضافة الموظف جديد", 0);
            return prepareList();
        } catch (Exception e) {
            loger.LogerString("خطاء في اضافة الموظف جديد", 1);
            loger.LogerString("EmployeeController : Create : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Employee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String Reset() {
        current = (Employee) getItems().getRowData();
        current.setPass("111111");
        update();
        return "List";
    }

    public String update() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("EmployeeUpdated"));
            loger.LogerString(" تم تعديل الموظف بنجاح", 0);
            return "List";
        } catch (Exception e) {
            loger.LogerString("خطاء في تعديل الموظف", 1);
            loger.LogerString("EmployeeController : update : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Employee) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "List";
        } else {
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle1").getString("EmployeeDeleted"));
            loger.LogerString("تم حذف الموظف بنجاح", 0);
        } catch (Exception e) {
            loger.LogerString("خطاء في حذف الموظف", 1);
            loger.LogerString("EmployeeController : Destroy : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle1").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Employee.class)
    public static class EmployeeControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            EmployeeController controller = (EmployeeController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "employeeController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Employee) {
                Employee o = (Employee) object;
                return getStringKey(o.getIdEmployee());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + EmployeeController.class.getName());
            }
        }
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String logOut() {
        try {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
            if (session != null) {
                session.invalidate();
            }
            return "/login?faces-redirect=true";
        } catch (Exception e) {
            return "/login?faces-redirect=true";
        }

    }

    public String loginCheck() {
        String userName = getUserName();
        String pass = getPassword();
        String page = "login?faces-redirect=true";
        session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        Employee emp = getFacade().checkUserLogin(userName, pass);
        if (emp != null) {
            session.putValue("userName", emp.getUserName());
            session.putValue("empid", emp.getIdEmployee());
            session.putValue("name", emp.getName());
            session.putValue("limits", emp.getLimits());
            if (!emp.getPass().equals("111111")) {
                page = "/bill/CustomerBill?faces-redirect=true";
            } else {
                current = emp;
                page = "/employee/Edit";
            }
        } else {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("InvalidLogin"));

        }
        return page;
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }
}
